﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Globalization;
using System.Xml;

namespace Light.Utility
{
    public class StringHelper
    {
        public static string Amead(string s, char sp)
        {
            if (string.IsNullOrEmpty(s) || (s.Length <= 1))
            {
                return s;
            }
            StringBuilder builder = new StringBuilder();
            bool flag = false;
            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];
                if ((i > 0) && char.IsUpper(c))
                {
                    if (!flag)
                    {
                        builder.Append(sp);
                        flag = true;
                    }
                }
                else
                {
                    flag = false;
                }
                builder.Append(c);
            }
            return builder.ToString();
        }

        public static int Count(string s1, string s2)
        {
            int num = 0;
            if (!string.IsNullOrEmpty(s1) && !string.IsNullOrEmpty(s2))
            {
                int index = -1;
                do
                {
                    index = s1.IndexOf(s2, (int)(index + 1));
                    if (index != -1)
                    {
                        num++;
                    }
                }
                while ((index != -1) && ((index + 1) < s1.Length));
            }
            return num;
        }

        public static object FromBase64(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {
                return Serializer.Deserialize(Convert.FromBase64String(data));
            }
            return null;
        }

        public static string ToBase64(object obj)
        {
            if (obj != null)
            {
                byte[] inArray = Serializer.Serialize(obj);
                if ((inArray != null) && (inArray.Length != 0))
                {
                    return Convert.ToBase64String(inArray);
                }
            }
            return null;
        }

        public static bool IsDateTime(object value)
        {
            DateTime time;
            if (value == null || string.IsNullOrEmpty(value.ToString()) || value.ToString().Length < 8)
            {
                return false;
            }
            string strValue = value.ToString().Trim();
            if (strValue.Length == 0)
            {
                return false;
            }
            return DateTime.TryParse(strValue, out time);
        }

        public static bool IsEmailAddress(object address)
        {
            if (address == null)
            {
                return false;
            }
            string pattern = @"\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$";
            Regex regex = new Regex(pattern);
            return regex.Match(address.ToString()).Success;
        }

        public static bool IsMobileNumber(object number)
        {
            if (number == null)
            {
                return false;
            }
            string pattern = @"(^0?[1][34578][0-9]{9}$)";
            Regex regex = new Regex(pattern);
            return regex.Match(number.ToString()).Success;
        }

        public static bool IsNumeric(char c)
        {
            return char.IsDigit(c);
        }

        public static bool IsNumeric(object value)
        {
            if (value == null || String.IsNullOrEmpty(value.ToString()))
            {
                return false;
            }
            string str = value.ToString().Trim().TrimStart(new char[] { '+', '-' });
            if (str.Length == 0)
            {
                return false;
            }
            bool flag = false;
            for (int i = 0; i < str.Length; i++)
            {
                char c = str[i];
                if ((c != ',') || (i <= 0))
                {
                    if (c == '.')
                    {
                        if ((i == 0) || flag)
                        {
                            return false;
                        }
                        flag = true;
                    }
                    else if (!IsNumeric(c))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        public static bool IsNumeric(object value, NumberStyles NumberStyle)
        {
            double num;
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return false;
            }
            string strValue = value.ToString();
            value = strValue.Trim();
            if (strValue.Length == 0)
            {
                return false;
            }
            return double.TryParse(strValue, NumberStyle, CultureInfo.CurrentCulture, out num);
        }

        public static bool IsURL(object url)
        {
            if (url == null)
            {
                return false;
            }
            string pattern = @"\b(\S+)://(\S+)(?::(\S+))?\b";
            Regex regex = new Regex(pattern);
            return regex.Match(url.ToString()).Success;
        }

        public static string Join(string separator, IList value)
        {
            return Join(separator, value, ' ');
        }

        public static string Join(string separator, IList value, char valueMark)
        {
            if (string.IsNullOrEmpty(separator))
            {
                throw new ArgumentNullException("separator");
            }
            if ((value == null) || (value.Count == 0))
            {
                return string.Empty;
            }
            StringBuilder builder = new StringBuilder();
            foreach (object obj2 in value)
            {
                if (obj2 != null)
                {
                    string str = obj2.ToString();
                    if (str.Length != 0)
                    {
                        if (builder.Length != 0)
                        {
                            builder.Append(separator);
                        }
                        if (char.IsPunctuation(valueMark))
                        {
                            builder.Append(valueMark);
                        }
                        builder.Append(str);
                        if (char.IsPunctuation(valueMark))
                        {
                            builder.Append(valueMark);
                        }
                    }
                }
            }
            return builder.ToString();
        }

        public static string PadRight(string s, int totalWidth, char paddingChar)
        {
            if (s == null)
            {
                s = string.Empty;
            }
            return s.PadRight(totalWidth, paddingChar);
        }

        public static int SingleComputeLength(string s)
        {
            int byteCount = 0;
            if (s != null)
            {
                byteCount = Encoding.Default.GetByteCount(s);
            }
            return byteCount;
        }

        public static string SinglePadRight(string s, int totalWidth, char paddingChar)
        {
            if (s == null)
            {
                s = string.Empty;
            }
            int num = SingleComputeLength(s);
            int count = totalWidth - num;
            if (count <= 0)
            {
                return s;
            }
            string str = new string(paddingChar, count);
            return (s + str);
        }

        public static string SingleSubstring(string s, int startIndex, int length)
        {
            if (s == null)
            {
                return null;
            }
            byte[] bytes = Encoding.Default.GetBytes(s);
            int num = bytes.Length - startIndex;
            if (num < length)
            {
                length = num;
            }
            byte[] destinationArray = new byte[length];
            Array.Copy(bytes, startIndex, destinationArray, 0, length);
            return Encoding.Default.GetString(destinationArray);
        }

        /// <summary>
        /// 按间隔数量插入指定字符
        /// </summary>
        /// <param name="input"></param>
        /// <param name="interval"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string InsertFormat(string input, int interval, string value)
        {
            for (int i = interval; i < input.Length; i += interval + 1)
                input = input.Insert(i, value);
            return input;
        }

        public static Dictionary<string, string> StringParToDictionary(string s, char separ1, char separ2)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(s))
            {
                string[] strArray = s.Split(new char[] { separ1 });
                foreach (string str in strArray)
                {
                    string[] strArray2 = str.Split(new char[] { separ2 });
                    if (strArray2.Length != 0)
                    {
                        strArray2[0] = strArray2[0].Trim();
                        if (strArray2[0].Length != 0)
                        {
                            string str2 = string.Empty;
                            if (strArray2.Length > 1)
                            {
                                str2 = str.Remove(0, str.IndexOf(separ2) + 1).Trim();
                            }
                            string key = strArray2[0];
                            if (!dictionary.Keys.Contains(key))
                            {
                                dictionary.Add(key, str2);
                            }
                        }
                    }
                }
            }
            return dictionary;
        }

        /// <summary>
        /// string转int集合（仅取大于0的值）
        /// </summary>
        /// <param name="input"></param>
        /// <param name="separ"></param>
        /// <param name="gtZero"></param>
        /// <returns></returns>
        public static IList<int> ToIntList(string input, char separ)
        {
            return ToIntList(input, separ, false, false);
        }


        /// <summary>
        /// string转int集合
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <param name="separ">分割符</param>
        /// <param name="gtZero">是否只取大于0的数据</param>
        /// <param name="distinct">是否排重</param>
        /// <returns></returns>
        public static IList<int> ToIntList(string input, char separ, bool gtZero, bool distinct)
        {
            List<int> list = new List<int>();

            if (!String.IsNullOrEmpty(input))
            {
                string[] array = input.Split(separ);
                foreach (string item in array)
                {
                    int value = ToInt(item);
                    if (gtZero && value <= 0)
                        continue;
                    if (distinct && list.Contains(value))
                        continue;
                    list.Add(value);
                }
            }

            return list;
        }

        public static string ToDBC(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            char[] chArray = input.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                if (chArray[i] == '　')
                {
                    chArray[i] = ' ';
                }
                else if ((chArray[i] > 0xff00) && (chArray[i] < 0xff5f))
                {
                    chArray[i] = (char)(chArray[i] - 0xfee0);
                }
            }
            return new string(chArray);
        }

        public static string ToSBC(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            char[] chArray = input.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                if (chArray[i] == ' ')
                {
                    chArray[i] = '　';
                }
                else if (chArray[i] < '\x007f')
                {
                    chArray[i] = (char)(chArray[i] + 0xfee0);
                }
            }
            return new string(chArray);
        }

        public static string Truncate(string s, int length)
        {
            if (string.IsNullOrEmpty(s))
            {
                return s;
            }
            if (length <= 0)
            {
                return string.Empty;
            }
            if (length >= s.Length)
            {
                return s;
            }
            int startIndex = length;
            int num2 = s.Length - startIndex;
            StringBuilder builder = new StringBuilder(s);
            builder = builder.Remove(startIndex, num2);
            if (builder.Length > 3)
            {
                builder = builder.Remove(builder.Length - 3, 3);
                builder.Append("...");
            }
            return builder.ToString();
        }

        public static decimal ToDecimal(object str)
        {
            if (str == null || IsNumeric(str) == false)
                return 0;
            else
                return Convert.ToDecimal(str);
        }

        public static double ToDouble(object str)
        {
            if (str == null || IsNumeric(str) == false)
                return 0;
            else
                return Convert.ToDouble(str);
        }

        public static int ToInt(object str)
        {
            if (str == null || IsNumeric(str) == false)
                return 0;
            else
                return Convert.ToInt32(ToDecimal(str));
        }

        public static string ToString(object str)
        {
            if (str == null)
                return string.Empty;
            else
                return str.ToString();
        }

        public static DateTime ToDateTime(object str)
        {
            if (str == null || IsDateTime(str) == false)
                return default(DateTime);
            else
                return DateTime.Parse(str.ToString());
        }

        public static DateTime ToDateTime(object str, DateTime defaultValue)
        {
            DateTime dt = ToDateTime(str);
            if (dt == default(DateTime))
                dt = defaultValue;

            return dt;
        }

        public static DateTime ToDateTime(object str, string formatString)
        {
            if (str == null)
            {
                return default(DateTime);
            }
            else
            {
                return XmlConvert.ToDateTime(str.ToString(), formatString);
            }
        }

        /// <summary>
        /// 截取双精度值的指定位数字
        /// </summary>
        /// <param name="money"></param>
        /// <param name="index">千位：4 ，百位：3，十位：2，个位：1 ，小数位1位：-1，小数位2位：-2，....</param>
        /// <returns>指定位数字</returns>
        public static string SubDecimalPart(decimal money, int index)
        {
            string result = string.Empty;

            string monetyStr = money.ToString("F8");

            string partGtZero = monetyStr.Split('.')[0];
            string partLtZero = monetyStr.Split('.')[1];

            if (partGtZero.Length >= index && index > 0)
            {
                result = partGtZero.Substring(partGtZero.Length - index, 1);

            }
            else if (index < 0 && partGtZero.Length > Math.Abs(index))
            {
                result = partLtZero.Substring(-1 - index, 1);
            }
            if (result == "0")
                result = "";

            return result;
        }


        /// <summary>
        /// 获取html代码中的图片地址
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns>图片地址s</returns>
        public static List<string> GetImageSources(string htmlContent)
        {
            List<string> result = new List<string>();

            //创建正则表达式规则获得所有图片地址
            Regex objRegExp = new Regex("(src|Src|SRC|sRC|SrC)[^>]*[^/].(?:jpg|bmp|gif|png)(?:\"|\')");

            //获得图片地址集合
            MatchCollection mc;
            mc = objRegExp.Matches(htmlContent);

            string str = string.Empty;
            int start = 0;
            int end = 0;

            //遍历插入到结果集中
            for (int i = 0; i < mc.Count; i++)
            {
                //取得: src="http://localhost:1635/UploadFiles/pic/2008829/633556161238906250.gif"
                //中的两个引号""之间的地址
                start = mc[i].Value.IndexOf("\"") + 1;//起始位置长度
                end = mc[i].Value.Length - start - 1;//总长度-开始位置的长度-最后“的长度
                str = mc[i].Value.Substring(start, end);

                if (str.Contains(" "))
                    str = str.Split(' ')[0];

                str = str.Replace("\"", "");

                result.Add(str);
            }
            return result;
        }

        /// <summary>
        /// 判断html代码中是否包含图片
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public static bool ContainsImage(string htmlContent)
        {
            Regex objRegExp = new Regex("(src|Src|SRC|sRC|SrC)[^>]*[^/].(?:jpg|bmp|gif|png)(?:\"|\')");
            return objRegExp.Match(htmlContent).Success;
        }



        /// <summary>
        /// 获取html代码中的超链接
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns>超链接s</returns>
        public static List<string> GetHyperLinks(string htmlContent)
        {
            List<string> result = new List<string>();

            //创建正则表达式规则获得所有图片地址
            Regex objRegExp = new Regex("href[^>]*[^/].(?:\"|\')", RegexOptions.IgnoreCase);

            //获得图片地址集合
            MatchCollection mc;
            mc = objRegExp.Matches(htmlContent);

            string str = string.Empty;
            int start = 0;
            int end = 0;

            //遍历插入到结果集中
            for (int i = 0; i < mc.Count; i++)
            {
                //取得: src="http://localhost:1635/UploadFiles/pic/2008829/633556161238906250.gif"
                //中的两个引号""之间的地址
                start = mc[i].Value.IndexOf("\"") + 1;//起始位置长度
                end = mc[i].Value.Length - start;//总长度-开始位置的长度-最后“的长度
                str = mc[i].Value.Substring(start, end);

                end = str.IndexOf("\"");
                if (end < 0)
                    continue;
                str = str.Substring(0, end);

                if (IsURL(str) && !result.Contains(str))
                    result.Add(str);
            }
            return result;
        }


        /// <summary>
        /// 匹配正则表达式
        /// </summary>
        /// <param name="str"></param>
        /// <param name="regexRule"></param>
        /// <returns></returns>
        public static bool IsMatched(string str, string regexRule)
        {
            Regex regex = new Regex(regexRule);
            return regex.Match(str).Success;
        }

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="strStart"></param>
        /// <param name="strEnd"></param>
        /// <returns></returns>
        public static string SubString(string str, string strStart, string strEnd)
        {
            int start = str.IndexOf(strStart) + 1;
            int end = str.IndexOf(strEnd) + strEnd.Length;
            return str.Substring(start, end);
        }

        /// <summary>
        /// 去掉字符串中的 空格，回车，换行，制表符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Trim(string str)
        {
            if (String.IsNullOrEmpty(str))
                return string.Empty;
            return str.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
        }

        /// <summary>
        /// 从文件的完整路径中获取文件名(包含扩展名)
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// <param name="includeExtension">是否包含扩展名</param>
        /// <returns></returns>
        public static string GetFileName(string fileFullPath, bool includeExtension)
        {
            if (!String.IsNullOrEmpty(fileFullPath))
            {
                string[] str = fileFullPath.Split('\\');
                string name = str[str.Length - 1];
                if (includeExtension)
                {
                    return name;
                }
                else
                {
                    return name.Split('.')[0];
                }
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetExtension(string fileName)
        {
            if (!String.IsNullOrEmpty(fileName))
            {
                string[] str = fileName.Split('.');
                return str[str.Length - 1];
            }
            else
            {
                return string.Empty;
            }
        }

        public static string Replace(object obj, string strOld, string strNew)
        {
            if (obj != null)
            {
                return obj.ToString().Replace(strOld, strNew);
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 截取字符串 如：1111W2222P3333G4444 结果为 1111,2222,3333,4444
        /// </summary>
        /// <param name="str"></param>
        /// <param name="separs">分隔符s</param>
        /// <returns></returns>
        public static string[] Split(string str, params char[] separs)
        {

            if (!String.IsNullOrEmpty(str))
            {
                int count = separs.Length;
                string[] array = new string[count + 1];

                for (int i = 0; i < count; i++)
                {
                    int start = 0;
                    int len = str.IndexOf(separs[i]);

                    if (i == 0)
                    {
                        start = 0;
                    }
                    else
                    {
                        start = str.IndexOf(separs[i - 1]) + 1;
                        len = str.IndexOf(separs[i]) - start;
                    }

                    if (len < 0)
                        throw new Exception("字符串 \"" + str + "\" 中不包含分隔符 '" + separs[i] + "'");
                    else
                        array[i] = str.Substring(start, len);

                    if (i == count - 1)
                    {
                        start = str.IndexOf(separs[i]) + 1;
                        len = str.Length - start;

                        array[count] = str.Substring(start, len);
                    }

                }

                return array;
            }
            else
            {
                return new string[] { };
            }
        }


        /// <summary>
        /// 生成订单编号（前缀 + yyMMddHHmm + (10000-99999)随机数）
        /// </summary>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public static string GetOrderNo(string prefix)
        {
            Random random = new Random(DateTime.Now.Second);
            return GetOrderNo(prefix, "yyMMddHHmm", random.Next(10000, 99999).ToString());
        }

        /// <summary>
        /// 生成订单编号（前缀 + 日期 + 后缀）
        /// </summary>
        /// <param name="prefix">前缀</param>
        /// <param name="dateFormatStr">日期格式</param>
        /// <param name="suffix">后缀</param>
        /// <returns></returns>
        public static string GetOrderNo(string prefix, string dateFormatStr, string suffix)
        {
            return prefix + DateTime.Now.ToString(dateFormatStr) + suffix;
        }

        /// <summary>
        /// 检测是否包含emoji表情字符
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool ContainsEmoji(string source)
        {
            if (String.IsNullOrEmpty(source))
            {
                return false;
            }

            int len = source.Length;

            for (int i = 0; i < len; i++)
            {
                char codePoint = source[i];

                if (isEmojiCharacter(codePoint))
                {
                    //do nothing，判断到了这里表明，确认有表情字符
                    return true;
                }
            }

            return false;
        }


        private static bool isEmojiCharacter(char codePoint)
        {
            return (codePoint == 0x0) ||
                    (codePoint == 0x9) ||
                    (codePoint == 0xA) ||
                    (codePoint == 0xD) ||
                    ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                    ((codePoint >= 0xE000) && (codePoint <= 0xFFFD));
        }

        /// <summary>
        /// 过滤emoji表情字符
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static String FilterEmoji(string source)
        {

            if (!ContainsEmoji(source))
            {
                return source;//如果不包含，直接返回
            }
            //到这里铁定包含
            StringBuilder builder = null;

            int len = source.Length;

            for (int i = 0; i < len; i++)
            {
                char codePoint = source[i];

                if (isEmojiCharacter(codePoint))
                {
                    if (builder == null)
                    {
                        builder = new StringBuilder(source.Length);
                    }

                    builder.Append(codePoint);
                }
                else
                {

                }
            }

            if (builder == null)
            {
                return source;//如果没有找到 emoji表情，则返回源字符串
            }
            else
            {
                if (builder.Length == len)
                {//这里的意义在于尽可能少的toString，因为会重新生成字符串
                    builder = null;
                    return source;
                }
                else
                {
                    return builder.ToString();
                }
            }
        }

        /// <summary>
        /// 验证是否为身份证号码
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static bool IsIDCardNumber(object str)
        {
            if (str == null)
                return false;

            string value = str.ToString();
            if (value.Length == 18)
            {
                bool check = IsIDCardNumber18(value);
                return check;
            }
            else if (value.Length == 15)
            {
                bool check = IsIDCardNumber15(value);
                return check;
            }
            else
            {
                return false;
            }
        }
        private static bool IsIDCardNumber18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }
        private static bool IsIDCardNumber15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }

        /// <summary>
        /// 判断字符串是否有中文字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool HasChineseWord(string str)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]");
            Match m = regex.Match(str);
            return m.Success;
        }

        /// <summary>
        /// 字符串转16进制字符串
        /// </summary>
        /// <param name="s"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string StringToHexString(string s, Encoding encode)
        {
            byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
            return StringToHexString(b);
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string StringToHexString(byte[] b)
        {
            string result = string.Empty;
            for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符
            {
                result += Convert.ToString(b[i], 16);
            }
            return result;
        }

        /// <summary>
        /// 16进制转指定编码的字符串
        /// </summary>
        /// <param name="hs"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string HexStringToString(string hs, Encoding encode)
        {
            //以%分割字符串，并去掉空字符
            string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] b = new byte[chars.Length];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < chars.Length; i++)
            {
                b[i] = Convert.ToByte(chars[i], 16);
            }
            //按照指定编码将字节数组变为字符串
            return encode.GetString(b);
        }



        ///// <summary>
        ///// 字符转拼音(使用此方法时需引用 CHPinYinConver.dll)
        ///// </summary>
        ///// <param name="str"></param>
        ///// <returns></returns>
        //public static string ToPinYin(string str)
        //{
        //    string result = string.Empty;
        //    Regex regex = new Regex("[\u4e00-\u9fa5]");
        //    foreach (char c in str)
        //    {
        //        Match m = regex.Match(c.ToString());
        //        if (m.Success)
        //        {
        //            result += CHPinYinConver.PinYinConver.ConvertToPinYin(c.ToString());
        //        }
        //        else
        //        {
        //            result += c.ToString();
        //        }
        //    }
        //    return result;
        //}
    }

}
